import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class GetDioHttp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetDioHttpState();
  }
}

class GetDioHttpState extends StatefulWidget {
  @override
  _GetDioHttpState createState() => _GetDioHttpState();
}

class _GetDioHttpState extends State<GetDioHttpState> {
  //定义一个字符串
  String requestText = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("get请求"),
      ),
      body: Container(
        alignment: Alignment.topCenter,
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                RaisedButton(
                  onPressed: () {
                    getRequest();
                  },
                  child: Text("get请求"),
                ),
                RaisedButton(
                  onPressed: () {
                    postRequest();
                  },
                  child: Text("post请求"),
                )
              ],
            ),
            Text(
              requestText,
              style: TextStyle(fontSize: 12, color: Colors.indigo),
            )
          ],
        ),
      ),
    );
  }

  /*
   * dio get网络请求
   */
  Future<void> getRequest() async {
    Dio dio = Dio();
    final response = await dio.get("https://www.wanandroid.com/banner/json");
    print(response.toString());
    setState(() {
      requestText = response.toString();
    });
  }

  Future<void> postRequest() async {
    var path = "https://www.wanandroid.com/user/register";
    var params = {
      "username": "aa112233",
      "password": "123456",
      "repassword": "123456"
    };
    Response response = await Dio().post(path, queryParameters: params);
    this.setState(() {
      requestText = response.toString();
    });
  }
}
